package com.zdp.middleware.ratelimiter.valve.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import com.zdp.middleware.ratelimiter.Constants;
import com.zdp.middleware.ratelimiter.annotation.DoRateLimiter;
import com.zdp.middleware.ratelimiter.valve.IValveService;
import org.aspectj.lang.ProceedingJoinPoint;

import java.lang.reflect.Method;

/**
 * @author ZhengDp
 * @Date 2023/5/27 15:34
 */
public class RateLimiterValve implements IValveService {
    @Override
    public Object access(ProceedingJoinPoint jp, Method method, DoRateLimiter doRateLimiter, Object[] args) throws Throwable {
        if( 0 == doRateLimiter.permitsPerSecond()) {
            return jp.proceed();
        }

        String clazzName = jp.getTarget().getClass().getName();
        String methodName = method.getName();
        String key = clazzName + "." + methodName;
        // 这里应该对key进行加锁，避免重复创建
        if(null == Constants.rateLimiterMap.get(key)) {
            // 该请求第一次进入
            Constants.rateLimiterMap.put(key, RateLimiter.create(doRateLimiter.permitsPerSecond()));
        }

        RateLimiter rateLimiter = Constants.rateLimiterMap.get(key);
        if(rateLimiter.tryAcquire()) {
            return jp.proceed();
        }
        return JSON.parseObject(doRateLimiter.returnJson(),method.getReturnType());
    }
}
